package com.chanel.iamframework.core.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.validation.constraints.NotNull;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chanel.iamframework.core.dao.UserDAO;
import com.chanel.iamframework.core.domain.Group;
import com.chanel.iamframework.core.domain.User;
import com.chanel.iamframework.core.service.UserService;

public class UserServiceImpl implements UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	private UserDAO userDAO;
	
	public UserServiceImpl(@NotNull UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Override
	public User getUser(Long userId) {
		return userDAO.getUser(userId);
	}

	@Override
	public void createUser(User user) {
		userDAO.createUser(user);
	}

	@Override
	public boolean deleteUser(Long userId) {
		return userDAO.deleteUser(userId) > 0 ? true : false;
	}

	@Override
	public boolean updateUser(User user) {
		return userDAO.updateUser(user) > 0 ? true : false;
	}

	@Override
	public User loadGroups(Long userId) {
		return userDAO.loadGroups(userId);
	}

	@Override
	public User loadApplications(Long userId) {
		return userDAO.loadApplications(userId);
	}

	@Override
	public User loadRoles(Long userId) {
		return userDAO.loadRoles(userId);
	}
	
	@Override
	public void addGroups(User user) {
		if (CollectionUtils.isEmpty(user.getGroups())) {
			logger.debug("user.groups is empty");
		} else {
			logger.debug("user.groups contain {} groups", user.getGroups().size());
			for (Group group: user.getGroups()) {
				userDAO.addGroup(group.getGroupId(), user.getUserId());
				logger.debug("association ({}, {}) created", user, group);
			}
		}
	}

	@Override
	public boolean deleteGroups(User user) {
		boolean deletedGroups = false;
		
		if (CollectionUtils.isEmpty(user.getGroups())) {
			logger.debug("user.groups is empty");
		} else if (userDAO.getUser(user.getUserId()) == null) {
			logger.debug("userId={} not exist", user.getUserId());
		} else {
			List<Group> groupsToBeDeleted = new ArrayList<Group>();
			
			logger.debug("user.groups contain {} groups", user.getGroups().size());
			for (Group group: user.getGroups()) {
				if (userDAO.deleteGroup(group.getGroupId(), user.getUserId()) > 0) {
					groupsToBeDeleted.add(group);
					logger.debug("association ({}, {}) deleted", user, group);
				} else {
					logger.debug("association ({}, {}) not found", user, group);
				}
			}
			
			user.getGroups().removeAll(groupsToBeDeleted);
			deletedGroups = groupsToBeDeleted.size() > 0;
		}
		
		return deletedGroups;
	}

}
